﻿using System.Web.Mvc;
using GBlog.Core.Recaptcha;
namespace GBlog.Core.Attributes
{
    public class CaptchaValidatorAttribute : ActionFilterAttribute
    {
        private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
        private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
        private RecaptchaResponse recaptchaResponse;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            RecaptchaValidator recaptchaValidator = new RecaptchaValidator();
            recaptchaValidator.PrivateKey = RecaptchaControlMvc.PrivateKey;
            recaptchaValidator.RemoteIP = filterContext.HttpContext.Request.UserHostAddress;
            recaptchaValidator.Challenge = filterContext.HttpContext.Request.Form["recaptcha_challenge_field"];
            recaptchaValidator.Response = filterContext.HttpContext.Request.Form["recaptcha_response_field"];
            if (string.IsNullOrEmpty(recaptchaValidator.Challenge))
            {
                this.recaptchaResponse = RecaptchaResponse.InvalidChallenge;
            }
            else
            {
                if (string.IsNullOrEmpty(recaptchaValidator.Response))
                {
                    this.recaptchaResponse = RecaptchaResponse.InvalidResponse;
                }
                else
                {
                    this.recaptchaResponse = recaptchaValidator.Validate();
                }
            }
            filterContext.ActionParameters["captchaValid"] = this.recaptchaResponse.IsValid;
            filterContext.ActionParameters["captchaErrorMessage"] = this.recaptchaResponse.ErrorMessage;
            base.OnActionExecuting(filterContext);
        }
    }
}